package com.netease.account.email;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import com.netease.exception.AccountEmailException;

public class AccountEmailServiceImpl implements AccountEmailService {

    private JavaMailSender javaMailSender;

    private String systemEmail;

    /**
     * @return the javaMailSender
     */
    public JavaMailSender getJavaMailSender() {
        return javaMailSender;
    }

    /**
     * @param javaMailSender
     *            the javaMailSender to set
     */
    public void setJavaMailSender(JavaMailSender javaMailSender) {
        this.javaMailSender = javaMailSender;
    }

    /**
     * @return the systemEmail
     */
    public String getSystemEmail() {
        return systemEmail;
    }

    /**
     * @param systemEmail
     *            the systemEmail to set
     */
    public void setSystemEmail(String systemEmail) {
        this.systemEmail = systemEmail;
    }

    public void sendEmail(String to, String subject, String htmlText)
            throws AccountEmailException {
        try {
            MimeMessage msg = javaMailSender.createMimeMessage();
            MimeMessageHelper msgHelper = new MimeMessageHelper(msg);

            msgHelper.setFrom(systemEmail);
            msgHelper.setTo(to);
            msgHelper.setSubject(subject);
            msgHelper.setText(htmlText, true);
        } catch (MessagingException e) {
            throw new AccountEmailException("Faild to send mail.", e);
        }

    }
}
